﻿using AutoMapper;
using Sustainalytics.Entities.RiskRatings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Sustainalytics.ClientDW.Synchronization.SyncRiskRatingsData
{
    public class RiskRatingIndicatorMapping
    {
        public static IEnumerable<ComprehensiveRiskRatingIndicator> Map(
            IList<SharedEntities.RiskRatingsResearch.ComprehensiveRiskRatingResearchProfile> riskRatingResearchProfile)
        {
            return riskRatingResearchProfile.SelectMany(MapIssues);
        }

        private static IList<ComprehensiveRiskRatingIndicator> MapIssues(
            SharedEntities.RiskRatingsResearch.ComprehensiveRiskRatingResearchProfile entity)
        {
            var entities = entity.MaterialEsgIssues.SelectMany(MapIndicators).ToList();

            Parallel.ForEach(entities, mei =>
            {
                mei.CompanyId = entity.Id;
                mei.ExternalId = entity.CompanyId;
                mei.AggregatedWeight = mei.AggregatedWeight;
                mei.AggregatedWeightedScore = mei.AggregatedWeightedScore;
                mei.WeightedScoreInMei = mei.WeightedScoreInMei;
            });

            return entities;
        }

        private static IList<ComprehensiveRiskRatingIndicator> MapIndicators(
           SharedEntities.RiskRatingsResearch.MaterialEsgIssue entity)
        {
            var entities = entity.Indicators.Select(Mapper.Map<ComprehensiveRiskRatingIndicator>).ToList();

            Parallel.ForEach(entities, mei =>
            {
                mei.MeiExternalId = entity.ExternalId;
            });

            return entities;
        }
    }
}
